package com.example.springboot.service.impl;

import com.example.springboot.controller.request.BookPageRequest;
import com.example.springboot.entity.Book;
import com.example.springboot.mapper.BookMapper;
import com.example.springboot.service.IBookService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class BookService implements IBookService {
    @Resource
    BookMapper bookMapper;
    @Override
    public List<Book> list() {
        return bookMapper.list();
    }

    @Override
    public Object page(BookPageRequest bookPageRequest) {
        PageHelper.startPage(bookPageRequest.getPageNum(),bookPageRequest.getPageSize());
        List<Book> book = bookMapper.listByCondition(bookPageRequest);
        return new PageInfo<>(book);
    }

    @Override
    public void save(Book book) {
        // 根据 title 查询书籍
        Book existingBook = bookMapper.findByTitle(book.getTitle());
        if (existingBook == null) {
            // 如果书籍不存在，则保存
            bookMapper.save(book);
        } else {
            // 如果书籍存在，则更新 totalCopies
            int newTotalCopies = existingBook.getTotalCopies() + book.getTotalCopies();
            existingBook.setTotalCopies(newTotalCopies);
            bookMapper.updateTotalCopies(existingBook);
        }
    }

    @Override
    public boolean borrowBook(Long bookId) {
        Book book = bookMapper.findById(bookId);
        if (book != null && book.getTotalCopies() > 0) {
            book.setTotalCopies(book.getTotalCopies() - 1);
            bookMapper.updateTotalCopies(book);
            return true;
        }
        return false;
    }

    @Override
    public boolean updateBook(Long bookId, Book book) {
        Book existingBook = bookMapper.findById(bookId);
        if (existingBook != null) {
            //book.setBookId(id); // 确保更新时使用正确的 ID
            bookMapper.updateBook(book);
            return true;
        }
        return false;
    }

    @Override
    public boolean incrementTotalCopiesByTitle(String title) {
        try {
            bookMapper.incrementTotalCopiesByTitle(title);
            return true;
        } catch (Exception e) {
            return false;
        }
    }


    @Override
    public boolean canBorrowBook(Long bookId) {
        Book book = bookMapper.findById(bookId);
        return book.getTotalCopies() > 0;
    }


}
